package com.fresh.system.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fresh.common.ResponseResult;
import com.fresh.entity.Cart;
import com.fresh.entity.CartItem;
import com.fresh.entity.FreshGoods;
import com.fresh.system.until.GoodsClient;
import com.fresh.system.until.JedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Wx
 * @Date:2023/08/08/17:15
 * @Description:
 */
@RestController
@RequestMapping("cart")
public class CartController {
        @Resource
        private JedisClient jedisClient;
        @Resource
        private GoodsClient goodsClient;
        @Autowired
        RedisTemplate redisTemplate;
        private static final String REDIS_CART = "cart";



        /**
         * 商品加入到购物车
         * */
        @RequestMapping("/addProductToCart")
        @ResponseBody
        public ResponseResult addProductToCart(@RequestParam("goodsId")Integer goodsId, @RequestParam(value = "nums",required = false)Integer nums,HttpServletRequest httpServletRequest) throws JsonProcessingException {
            //获取已登录的用户信息
//            String userId = httpServletRequest.getHeader("userId");
            String userId = "1";
            FreshGoods goods = JSONObject.parseObject(new ObjectMapper().writeValueAsString(goodsClient.selectById(goodsId).getData()),FreshGoods.class);
            System.out.println(goods);
            /**
             * 查看redis的hash表中是否存在包含用户id的购物车数据
             * */
//            Boolean hexists = jedisClient.hexists(userId, String.valueOf(goodsId));
            Boolean hexists = jedisClient.hexists(REDIS_CART, userId);
            System.out.println("hexists---->" + hexists);
            Cart cart = null;
            if (nums == null || nums.equals("")) {
                nums = 1;
            }
            if (hexists) {
                //获取redis中userId对应goodId应的值
//                cart = JSON.parseObject(jedisClient.hget(userId, String.valueOf(goodsId)), Cart.class);
                CartItem cartItem = JSON.parseObject(jedisClient.hget(REDIS_CART, userId),CartItem.class);
                cart=cartItem.getCartMap().get(goodsId.toString());
                System.out.println(cart);
                Cart cart1 = new Cart();
                cart1.setId(goodsId);
                cart1.setGoodsId(goodsId);
                cart1.setGoodsName(goods.getName());
                //计算总数量
                cart1.setNums(cart.getNums() + nums);
                //计算总价格
                cart1.setTotalPrice(cart.getTotalPrice().add(goods.getPrice().multiply(BigDecimal.valueOf(nums))));
                cartItem.getCartMap().put(String.valueOf(goodsId),cart1);
                jedisClient.hset(REDIS_CART,userId,JSON.toJSONString(cartItem));
            } else {
                Cart cart1 = new Cart();
                cart1.setId(goodsId);
                cart1.setGoodsId(goodsId);
                cart1.setGoodsName(goods.getName());
                cart1.setNums(nums);
                cart1.setTotalPrice(goods.getPrice().multiply(BigDecimal.valueOf(nums)));
                CartItem cartItem=new CartItem();
                Map<String,Cart> cartMap=new HashMap<>();
                cartMap.put(String.valueOf(goodsId),cart1);
                cartItem.setCartMap(cartMap);
                jedisClient.hset(REDIS_CART, userId, JSON.toJSONString(cartItem));
            }
            return ResponseResult.success();
        }

        /**
         *购物车信息展示到前台购物车页
         * */
        @RequestMapping("/fromCartShowProduct")
        @ResponseBody
        public ResponseResult<List<Cart>> fromCartShowProduct( HttpServletRequest httpServletRequest){
            //获取已登录的用户信息
//            String userId = httpServletRequest.getHeader("userId");
            String userId="1";
//            JsonMapper jsonMapper=new JsonMapper();
//            List<Cart> list=new ArrayList<>();
//            try {
//                Cart cart = jsonMapper.readValue(jedisClient.get(userId), Cart.class);
//                list.add(cart);
//            } catch (JsonProcessingException e) {
//                throw new RuntimeException(e);
//            }

            CartItem cartItem = JSONObject.parseObject(jedisClient.hget(REDIS_CART, userId),CartItem.class);
            List<Cart> list=new ArrayList<>(cartItem.getCartMap().values());
            return ResponseResult.success(list);
        }


        /**
         * 删除购物车中某一个购物项
         * */
        @RequestMapping("/delCartProduct")
        @ResponseBody
        public ResponseResult delCartProduct(@RequestParam("goodsId")Integer goodsId, @RequestParam("nums")String nums, HttpServletRequest httpServletRequest){
            //获取已登录的用户信息
            String userId = httpServletRequest.getHeader("userId");
            CartItem cartItem = JSON.parseObject(jedisClient.hget(REDIS_CART,userId),CartItem.class);
            Cart cart = cartItem.getCartMap().get(goodsId);
            Cart cart1=new Cart();
            cart1.setId(goodsId);
            cart1.setNums(cart.getNums()-Integer.parseInt(nums));
            FreshGoods freshGoods=(FreshGoods) goodsClient.selectById(goodsId).getData();
            cart1.setTotalPrice(freshGoods.getPrice().multiply(BigDecimal.valueOf(cart.getNums()-Integer.parseInt(nums))));
            jedisClient.hset(REDIS_CART, userId, JSON.toJSONString(cartItem));
            return ResponseResult.success();
        }

}
